<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

    <input id="msg" type="text"/>
    <button type="button" onclick="sendMessage()">发送</button>

    <script>
        let ws = null;

        // 1.创建WebSocket对象，并指定服务器端程序（封装方法）
        function connect() {
            // 1）定义服务器端程序连接地址
            let target = "ws://localhost:8080/product-sys/hello";

            // 2）浏览器兼容判断
            if ('WebSocket' in window) {
                ws = new WebSocket(target);
            } else if ('MozWebSocket' in window) {
                ws = new MozWebSocket(target);
            } else {
                alert('WebSocket is not supported by this browser.');
                return;
            }
        }

        // 调用
        connect();

        // 2.客户端向服务器发送数据：WebSocket对象.send(消息) ;
        function sendMessage() {
            let msgTxt = document.getElementById("msg");
            if (ws != null) {
                // 发送消息
                ws.send(msgTxt.value);
                msgTxt.value = "";
                msgTxt.focus();
            } else {
                alert("WebSocket未连接，请连接");
            }
        }

        // 3.客户端接收服务器端的数据
        ws.onmessage = function (event) {
            // console.log(event) ;
            // document.getElementById("result").innerHTML += event.data +"<br/>";
            console.log(event.data);
        };
    </script>
</body>

</html>